using System.Collections.Generic;
using Events;
using Globals;
using UnityEngine;
using Utils;

namespace Actions
{
    public class TargetSpawner : MonoBehaviour
    {
        public Transform[] SpawnPoints => spawnPoints;

        [SerializeField] private VoidEventChannel tutorialStartedEvent;
        
        [SerializeField] private Transform[] spawnPoints;
        [SerializeField] private int burstCount = 3;
        [SerializeField] private float spawnInterval = 3f;
        [SerializeField] private Transform[] candidatePrefabs;
        
        private Timer _spawnTimer;
        
        private int[] _spawnPointIndexes;


        private void Start()
        {
            enabled = false;
            
            _spawnPointIndexes = new int[spawnPoints.Length];
            for (int i = 0; i < spawnPoints.Length; i++)
            {
                _spawnPointIndexes[i] = i;
            }

            _spawnTimer = new Timer(spawnInterval, Spawn);
            
            tutorialStartedEvent.Raised += TutorialStartedEvent_Raised;
        }

        private void Update()
        {
            _spawnTimer.Tick();
        }

        private void OnDestroy()
        {
            tutorialStartedEvent.Raised -= TutorialStartedEvent_Raised;
        }
        
        private void TutorialStartedEvent_Raised()
        {
            enabled = true;
            Spawn();
        }

        private void Spawn()
        {
            _spawnTimer.Reset( GameObject.Find("DifficultyCom").GetComponent<DifficultyCom>().GetOutEnemy());
            
            Shuffle(_spawnPointIndexes);

            for (int i = 0; i < burstCount; i++)
            {
                // Decide enemy type
                Transform enemyPrefab = candidatePrefabs[Random.Range(0, candidatePrefabs.Length)];
                
                Transform spawnPoint = spawnPoints[_spawnPointIndexes[i]];
                SpawnEnemy(enemyPrefab, spawnPoint.position);
                GameObject.Find("EnemyInSound").GetComponent<EnemyInSound>().Play();
            }
        }

        private void SpawnEnemy(Transform enemyPrefab, Vector3 position)
        {
            Instantiate(enemyPrefab, position, Quaternion.identity);
        }

        private static void Shuffle(IList<int> indexes)
        {
            for (int i = 0; i < indexes.Count; i++)
            {
                int j = Random.Range(0, i + 1);
                (indexes[i], indexes[j]) = (indexes[j], indexes[i]);
            }
        }
    }
}
